﻿using RPCServer.Attributes;
using RPCServer.Struct;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RPCServer.Core
{
    class MObjectManager : Singleton<MObjectManager>
    {
        Dictionary<Type, SyncPool<object>> _pool = new();

        public MObjectManager()
        {
            Load();
        }

        void Load()
        {
            foreach (var asmb in MySystem.Instance.Assemblies)
            {
                foreach (var type in asmb.GetTypesWhitAttribute<MObjectAttribute>())
                {
                    _pool.Add(type, new SyncPool<object>(() => { return Activator.CreateInstance(type); }));
                }
            }
        }

        public T GetItem<T>()
        {
            Type type = typeof(T);
            MObjectAttribute mObjectATB = type.GetCustomAttribute<MObjectAttribute>();
            T retItem;
            if (mObjectATB == null)
            {
                LogManager.Instance.LogError("类型属性不是 MObject!");
                return default;
            }

            if (_pool[type].TryTake(out object item))
            {
                retItem = (T)item;
            }
            else
            {
                LogManager.Instance.LogError("TryTake 失败!");
                retItem = default;
            }
            return retItem;
        }

        public void RecycleItem<T>(T item)
        {
            Type type = typeof(T);
            MObjectAttribute mObjectATB = type.GetCustomAttribute<MObjectAttribute>();
            if (mObjectATB == null)
            {
                LogManager.Instance.LogError("类型属性不是 MObject!");
            }
            else
            {
                _pool[type].Recycle(item);
            }
        }
    }
}
